var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");
var path = require('path');
var webpack = require('webpack');
var fs = require('fs');
var uglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
var glob = require('glob');
var srcDir = path.resolve(process.cwd(), 'src');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var _ = require('lodash');
var HappyPack = require('happypack');
var vendorsJson = path.join(__dirname, "/public/dll/vendors.json");
var ignore = require('./ignore');
var ignoreBuild = require('./ignore.build');

var dev = process.env.NODE_ENV == 'development';

//扫描文件
//获取多页面的每个入口文件，用于配置中的entry
function getEntry() {
	var jsPath = path.resolve(srcDir, 'js/');
	var ComponentHtmlPath = path.resolve(srcDir, 'component');
	var ComponentCssPath = path.resolve(srcDir, 'css');
	var filesMainJs = glob.sync(path.resolve(jsPath, '**/*.js'));
	var filesComponentJs = glob.sync(path.resolve(jsPath, '**/**/*.js'));
	var filesComponentHtml = glob.sync(path.resolve(ComponentHtmlPath, '**/**/*.html'));
	var filesCss = glob.sync(path.resolve(ComponentCssPath, '**/**/*.less'));

	var AllFile = _.reject([].concat(filesMainJs, filesComponentJs),function (path) {
		let count = [];
		if(dev){
			count = _.filter(ignore,function (appPath) {
				return path.indexOf(appPath)  >= 0;
			});
		}else {
			count = _.filter(ignoreBuild,function (appPath) {
				return path.indexOf(appPath)  >= 0;
			});
			
		}
		return _.size(count) > 0;
	});

	files = _.transform(AllFile, function (r, item) {
		matchs = item.match(/(.+)\.js$/);
		if(dev){
			r[matchs[1].replace(jsPath + '/', '')] = ['webpack-hot-middleware/client?reload=true'].concat([item]);
		}else {
			r[matchs[1].replace(jsPath + '/', '')] = item;
		}
		
	}, {})
	
	// files2Css = _.transform(filesCss, function (r, item) {
	// 	matchs = item.match(/(.+)\.(less|css)$/);
	// 	r[matchs[1].replace(jsPath + '/', '')] = item;
	// }, {})
	// var dirs = fs.readdirSync(jsPath);
	//
	// var matchs = [], files = {};
	// dirs.forEach(function (item) {
	// 	matchs = item.match(/(.+)\.js$/);
	// 	console.log(matchs);
	// 	if (matchs) {
	// 		files[matchs[1]] = path.resolve(srcDir, 'js', item);
	// 	}
	// });
	console.log(files);
	// console.log(files2Css);
	return _.assign(files,{
		'common': ['css']
	});
}

//加速打包插件
function cHappypack(id, loaders) {
	return new HappyPack({
		id: id,
		debug: false,
		verbose: false,
		threads: 4,
		loaders: loaders
	})
}

// babel设置
const babel = {

	'presets': [
		[
			'es2015',
			{
				'modules': false
			}
		],
		'stage-2',
		// Stage 2 is "draft", 4 is finished, 0 is strawMan.
	],

	'plugins': ['transform-runtime',],

	'env': {
		'development': {
			'presets': [],
			'plugins': [],
		},
		'production': {
			'presets': [],
			'plugins': [],
		}
	}

};

if (process.env.NODE_ENV == 'development') { // 启用测试模式
	console.log('启用测试模式')
	babel.plugins.push('istanbul');
}
//其它设置
process.traceDeprecation = true
console.log('path:',path.join(__dirname, "/build/"))
//webpack 主要设置
console.log('dev',dev);
const config  = {
	entry: getEntry(),
	output: {
		path: path.join(__dirname, "/build/"),
		publicPath: "/",
		filename: "js/[name].js",
		crossOriginLoading: false, // 是否允许跨域加载[anonymous,use-credentials,false]
		chunkFilename:  'async/[name].js',
		sourceMapFilename: '[file].map'
	},
	resolve: {
		alias: {
			// jquery: srcDir + "/js/jquery/jquery.2.1.4.js",
			// bootstrap: srcDir + "/js/bootstrap/bootstrap-3.3.5.min.js",
		}
	},
	module: {
		rules: [
			{
				test: /\.(js|jsx)$/,
				include: [path.join(__dirname, "/src/js/")],
				// loader: 'babel-loader',
				// query: babel
				use: ['happypack/loader?id=JSX']
			},
			{ // 处理HTML关于src链接问题
				test: /\.(html)$/,
				include: [path.join(__dirname, "/src/component/")],
				use: ['happypack/loader?id=HTML']
			},
			// {
			// 	test: /\.(html)$/,
			// 	exclude: [path.join(__dirname, "/src/component/")],
			// 	use: 'text-loader'
			// },
			{
				test: /\.(jpg|jpeg|png|gif|svg)$/,
				include: [
					path.join(__dirname, "/src/img/"),
					path.join(__dirname, "/public/plugins/"),
				],
				use: [
					{
						loader: 'url-loader',
						query: {
							limit: 2000,
							name: 'assets/[name].[ext]'
						}
					}
				]
			},
			{
				test: /\.(svg|ico|woff|eot|ttf)$/,
				include: [
					path.join(__dirname, "/src/"),
					path.join(__dirname, "/public/plugins/"),
				],
				use: [
					{
						loader: 'url-loader',
						query: {
							limit: 1,
							name: 'fonts/[name].[ext]'
						}
					}
				]
			},
			{ // 独立CSS文件
				test: /\.(less)$/, // 标准的CSS编译
				include: [
					path.join(__dirname, "/src/css/"),
					path.join(__dirname, "/public/plugins/"),
				],
				loaders: ExtractTextPlugin.extract({
					fallback: 'style-loader',
					use: [{
						loader: 'css-loader',
						query: {
							modules: false,
							outputStyle: 'expanded',
							sourceMap: dev,
							sourceMapContents: dev
						}
					}, 'less-loader', 'postcss-loader']
				})
			},
			{ // 独立CSS文件
				test: /\.(css)$/, // 标准的CSS编译
				include: [
					path.join(__dirname, "/src/css/"),
					path.join(__dirname, "/public/plugins/"),
				],
				loaders: ExtractTextPlugin.extract({
					fallback: 'style-loader',
					use: [{
						loader: 'css-loader',
						query: {
							modules: false,
							outputStyle: 'expanded',
							sourceMap: dev,
							sourceMapContents: dev
						}
					}, 'postcss-loader']
				})
			}
		]
	},
	performance: { // 关闭hot更新导致文件过大提示
		hints: 'warning' // 性能提示[warning,error,false]
	},
	plugins: [
		new webpack.optimize.OccurrenceOrderPlugin(),
		new webpack.HotModuleReplacementPlugin(),
		new webpack.NoEmitOnErrorsPlugin(),
		new webpack.DefinePlugin({
			'process.env': {
				NODE_ENV: JSON.stringify(process.env.NODE_ENV),
			},
		}),
		new webpack.DllReferencePlugin({
			context: '/',
			manifest: require(vendorsJson)
		}),
		new webpack.LoaderOptionsPlugin({
			minimize: true,
			options: {
				// context:  path.join(__dirname, "/src/"),
				postcss: [require('autoprefixer')({
					browsers: ['> 1%', 'last 5 versions', 'Firefox ESR'],
					cascade: false
				})]
			}
		}),
		new ExtractTextPlugin({
			filename: 'css/[name].css',
			disable: false,
			allChunks: true
		}),
		cHappypack('HTML', ['text-loader']),
		cHappypack('ES3', ['es3ify-loader']),

		cHappypack('JSX', [{
			loader: 'babel-loader',
			query: babel
		}]),
	],
	node: {
		fs: 'empty',
	}
};
if(!dev){
	//压缩
	config.plugins.push(
		new webpack.optimize.UglifyJsPlugin({
		  exclude : /\.min\.js$/,
		  mangle  : true,
		  compress: {
		    warnings    : false,
		    screw_ie8   : true,
		    conditionals: true,
		    unused      : true,
		    comparisons : true,
		    sequences   : true,
		    dead_code   : true,
		    evaluate    : true,
		    if_return   : true,
		    join_vars   : true,
		  },
		  output  : {
		    comments: false
		  },
		})
	)
}else {
	console.log('process.env.NODE_ENV',process.env.NODE_ENV);
	_.set(config,'devtool','inline-source-map') //
	_.set(config,'cache',true)
	
}


module.exports = config;
